<?php
/**
 *
 * 重建搜索基础
 *
 * buildSearchBase.php
 * Created by IntelliJ IDEA.
 *
 * @author: hjh <hjh@jf.com>
 *
 * Date: 2017/10/30
 * Time: 10:04
 */

use Common\Bridge;
use lib\search\ElasticSearch;

require_once dirname(__DIR__) . "/cronBase.php";

class buildBaseSearch extends cronBase
{

    public static $PAGE_SIZE = 1000;
    public static $DB_TABLE = null;
    public static $PRIMARY_KEY = null;
    public static $DB_READ = \Common\Bridge::DB_CIRCLE_R;
    public static $DB_WRITE = \Common\Bridge::DB_CIRCLE_W;
    public static $SCRIPT_NAME = __FILE__;
    public static $SEARCH_CLASS = null;

    public function doDefault()
    {
        assert(!empty(static::$DB_TABLE));
        assert(!empty(static::$PRIMARY_KEY));

        global $argv;
        $name = $argv[1];
        if (empty($name)) {
            echo static::$SCRIPT_NAME . " [index_name]\n";
            exit;
        }

        $primaryKey = static::$PRIMARY_KEY;

        $pdo = Bridge::pdo(static::$DB_READ);
        $count = $pdo->select("max({$primaryKey})")
            ->from(static::$DB_TABLE)
            ->getValue();

        echo "DataCount: {$count}\n";

        if ($count > 0) {
            $page = ceil($count / static::$PAGE_SIZE);
            echo "buildCircleSearch Start!\n";
            for ($i = 1; $i <= $page; $i++) {

                $start = ($i - 1) * static::$PAGE_SIZE;
                $end = $start + static::$PAGE_SIZE;

                $pdo = Bridge::pdo(static::$DB_READ);
                $data = $pdo->select("*")
                    ->from(static::$DB_TABLE)
                    ->where(["{$primaryKey} >" => $start, "{$primaryKey} <=" => $end])
                    ->getAll();

                $pdo->close();
                Bridge::pdo(static::$DB_READ, 'force_close');
                $pdo = null;

                if (count($data) > 0) {
                    static::insertSearch($name, $primaryKey, $data);
                }

                sleep(1);
                echo "Process: {$i}/{$page}\r";
            }

            echo "\nDone!\n";
        }
    }

    public function insertSearch($name, $idKey, $data)
    {
        assert(!empty(static::$SEARCH_CLASS));

        static $num = 0;
        $head = "{\"index\":{\"_index\":\"{$name}\",\"_type\":\"list\",\"_id\":\"{id}\"}}";
        $query = "";
        foreach ($data as $row) {
            $tmp_head = str_replace('{id}', $row[$idKey], $head);

            $CLASS = static::$SEARCH_CLASS;

            $t_body = $CLASS::formatAddData($row[$idKey], $row);
            if ($t_body === false) {
                fwrite(STDERR, "{$CLASS} formatAddData failed: " . json_encode($row) . "\n");
                continue;
            }

            if (isset($t_body[$CLASS::FIELD_ID])) {
                unset($t_body[$CLASS::FIELD_ID]);
            }

            $query .= $tmp_head . "\n" . json_encode($t_body) . "\n";
            $num++;
        }

        $es = Bridge::search(Bridge::SEARCH_DEFAULT);
        $ret = $es->query("/_bulk", ElasticSearch::HTTP_POST, $query);
        if ($ret === false) {
            echo json_encode($es->getLastError()), "\n";
        }
    }
}